﻿using System;
using System.Web;
using System.IO;
using VioletDevelopmentLaboratory.Net.Web;
using VioletDevelopmentLaboratory.Net.Web.Configuration;

namespace VioletDevelopmentLaboratory.Net.Web.Component
{
	public abstract class FileDownloadHandlerBase : HandlerBase
	{
		// Methods
		public override void ProcessRequest(HttpContext context)
		{
			if (context == null)
			{
				throw new ArgumentNullException("context");
			}

			String componentID = BoardParameters.ComponentID;
			String fileID = BoardParameters.FileID;

			//파일아이디가 없으면 다운로드 불가
			if (String.IsNullOrEmpty(fileID))
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("Invalid FileID(0).");
				return;
			}

			//파일아이디가 Guid가 아니면 다운로드 불가
			if(!VUtility.IsGuid(fileID))
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("Invalid FileID(1).");
				return;
			}


			//콤포넌트아이디가 없으면 다운로드 불가
			if (String.IsNullOrEmpty(componentID))
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("Invalid ComponentID(0).");
				return;
			}

			Board currentBoard = Board.GetBoard(BoardParameters.ComponentID);

			if (currentBoard == null)
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("Invalid ComponentID(1).");
				return;
			}

			//파일정보 가져옴
			AttachmentFileInfo attachmentFileInfo = currentBoard.GetAttachmentFileManager().GetAttachmentFileInfo(fileID);

			//파일아이디가 잘못됨
			if (attachmentFileInfo == null)
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("Invalid FileID(2).");
				return;
			}

			#region 등록되지 않은 임시파일
			//콤포넌트에 등록된 파일이 아니므로 임시파일로 처리
			if (String.IsNullOrEmpty(attachmentFileInfo.RelationID))
			{
				//실제파일이 존재하면서 다운로드 허용
				if (attachmentFileInfo.UploadFile.PhysicalFile.Exists)
				{
					attachmentFileInfo.AddDownloadCount(1);

					context.Response.ContentType = "Application/UnKnown";

					if (context.Request.UserAgent.ToLower().IndexOf("msie") > -1 || context.Request.UserAgent.ToLower().IndexOf("applewebkit") > -1)
						context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode(attachmentFileInfo.UploadFile.OriginalFileName));
					else
						context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + attachmentFileInfo.UploadFile.OriginalFileName);

					context.Response.TransmitFile(attachmentFileInfo.UploadFile.PhysicalFile.FullName);
					return;
				}

				context.Response.ContentType = "Text/Html";
				context.Response.Write("File not found.");
				return;
			}
			#endregion


			#region 등록된 정식파일
			//여기부터 임시파일이 아닌 정상 등록된 파일 처리
			//실제파일이 없으면 다운로드 불가
			if (!attachmentFileInfo.UploadFile.PhysicalFile.Exists)
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("File not found.");
				return;
			}

			BoardThread currentThread = currentBoard.GetThread(attachmentFileInfo.RelationID);

			VBoardUserInfo currentUserInfo = GetVBoardUserInfoBridge().GetUserInfo();

			if (currentThread.IsSecret)
			{
				if (!(currentUserInfo.IsAdministrator ||
					currentUserInfo.IsSysop(currentBoard) ||
					(currentThread.ProviderUserKey == currentUserInfo.ProviderUserKey)))
				{
					context.Response.ContentType = "Text/Html";
					context.Response.Write("Deny(0).");
					return;
				}
			}

			//권한이 없으면 다운로드 불가
			if (!(currentUserInfo.IsAdministrator || currentUserInfo.IsSysop(currentBoard) || currentUserInfo.IsAuthorizedBy(currentBoard, BoardCommand.FileDownload)))
			{
				context.Response.ContentType = "Text/Html";
				context.Response.Write("Deny(1).");
				return;
			}

			//다운로드 허용
			attachmentFileInfo.AddDownloadCount(1);

			context.Response.ContentType = "Application/UnKnown";

			if (context.Request.UserAgent.ToLower().IndexOf("msie") > -1 || context.Request.UserAgent.ToLower().IndexOf("applewebkit") > -1)
				context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode(attachmentFileInfo.UploadFile.OriginalFileName));
			else
				context.Response.AppendHeader("Content-Disposition", "attachment;filename=" + attachmentFileInfo.UploadFile.OriginalFileName);

			context.Response.TransmitFile(attachmentFileInfo.UploadFile.PhysicalFile.FullName);
			#endregion
		}
	}
}
